function [grayBER, numBits] =Simpletrellis_PPM_BERtool(EbNo, maxNumErrs, maxNumBits)
%BERTOOLTEMPLATE Template for a BERTool simulation function.
%   This M-file is a template for a BERTool-compatible
%   simulation function.  To use the template, insert your
%   own code in the places marked "INSERT YOUR CODE HERE"
%   and save the result as a file on your MATLAB path.
%   Then use the Monte Carlo panel of BERTool to execute
%   the script.
%
%   For more information about this template and an example
%   that uses it, see the Communications Toolbox documentation.
%
%   See also BERTOOL, VITERBISIM.

% Copyright 1996-2004 The MathWorks, Inc.
% $Revision: 1.1.6.2 $ $Date: 2004/03/24 20:32:33 $

% Import Java class for BERTool.
import com.mathworks.toolbox.comm.BERTool;

% Initialize variables related to exit criteria.
totErr  = 0; % Number of errors observed
numBits = 0; % Number of bits processed

temp = 0;
% Simulate until number of errors exceeds maxNumErrs
% or number of bits processed exceeds maxNumBits.

adj = 0.1/EbNo;

while((totErr < maxNumErrs) && (numBits < maxNumBits))

   % Check if the user clicked the Stop button of BERTool.
   if (BERTool.getSimulationStop)
      break;
   end
  
    % Random Data Generator
   N = 1000;
   input = genrandbits(N);
   output = rand(1, N);


    % Simple Trellis Encoder
   trellis = struct('numInputSymbols',2,'numOutputSymbols',4,...
   'numStates',4,'nextStates',[0 2;0 2;1 3;1 3],...
   'outputs',[0 3;1 2;3 0;2 1]);
    
   initial_state=0;

for i=1:N

   next_state=trellis.nextStates(initial_state+1,input(i)+1);
   output(i)=trellis.outputs(initial_state+1,input(i)+1);
   initial_state=next_state;
end


    %Generate 4-PPM wave
    a = ppm_mod(4, output);

    %% Channel
    % Send signal over an lognormal channel.
    %  EbNo = 10; % In dB   % COMMENT OUT FOR BERTOOL
    b = apply_lognormal(adj, a);


    % PPM Demodulator
     c = ppm_demod(4, b);

     % Viterbi Decoder
     d = viterbi_decode42(c);
     [number_of_errors temp] = calc_ber(d, input);

    % Update totErr and numBits.
    totErr = totErr + number_of_errors;
    numBits = numBits + N;
end % End of loop

% Compute the BER.
grayBER = totErr/numBits;
